#ifndef __THREAD__
#define __THREAD__

//线程封装
#include <iostream>
#include <pthread.h>
#include <string>
#include <functional>
#include <unistd.h>


namespace ThreadModule
{

    using func_t = std::function<void(std::string &)>;

    class Thread
    {
    public:
    void Excute()
    {
        _func(_threadname);
    }
    public:
        Thread(func_t func,const std::string &name = "none-name")
            :_func(func),_threadname(name),_stop(true)
        {}

        static void *threadroutine(void *args)//注意类成员函数默认的一个参数this指针，所以这里不满足原生线程库的参数即：一个参数void *args，所以要加上static
        {
            //所以在pthread_create的时候传的参数时this
            Thread *self = static_cast<Thread*>(args);
            self->Excute();
            return nullptr;
        }
        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, threadroutine, this);
            if (!n)
            {
                _stop = false;
                return true;
            }
            else
            {
                return false;
            }
        }

        void Join()
        {
            if (!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }

        void Stop()
        {
            _stop = true;
        }

        void Detach()
        {
            if (!_stop)
            {
                pthread_detach(_tid);
            }
        }

        std:: string name()
        {
            return _threadname;
        }
        ~Thread()
        {}
    private:
        pthread_t _tid;
        std::string _threadname;
        func_t _func;
        bool _stop;
    };
}


#endif